package com.syq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.syq.mapper.DtsAdminMapper;
import com.syq.mapper.DtsRoleMapper;
import com.syq.pojo.DtsAdmin;
import com.syq.pojo.DtsRole;
import com.syq.service.DtsRoleService;
import com.syq.vo.CatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: DtsRoleServiceImpl
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/7/22 9:26
 */

@Service
@Transactional
public class DtsRoleServiceImpl implements DtsRoleService {

    @Autowired
    private DtsRoleMapper dtsRoleMapper;

    @Autowired
    private DtsAdminMapper dtsAdminMapper;

    @Override
    public Set<String> findRolesByUid(Integer id) {
        DtsAdmin dtsAdmin = dtsAdminMapper.selectById(id);
        Integer[] roleIds = dtsAdmin.getRoleIds();
        if (roleIds!=null){
            List<DtsRole> dtsRoles = dtsRoleMapper.selectList(new QueryWrapper<DtsRole>()
                    .select("name")
                    .in("id", roleIds)
                    .eq("deleted", false)
            );

            if (!CollectionUtils.isEmpty(dtsRoles)){

                return dtsRoles.stream().map(DtsRole::getName).collect((Collectors.toSet()));
            }

        }
        return null;
    }

    @Override
    public List<CatVo> findAllRole() {
        return dtsRoleMapper.findAllRole();
    }

    @Override
    public IPage<DtsRole> findByPage(Integer page, Integer limit, String name, String sort, String order) {
        return dtsRoleMapper.selectPage(new Page<DtsRole>(page,limit),
                new QueryWrapper<DtsRole>()
                        .like(!StringUtils.isEmpty(name),"username",name)
                        .orderBy(!StringUtils.isEmpty(sort),order.equalsIgnoreCase("Asc"),sort));
    }

    @Override
    public void addRole(DtsRole dtsRole) {
        dtsRoleMapper.insert(dtsRole);
    }

    @Override
    public void update(DtsRole dtsRole) {
        dtsRoleMapper.update(dtsRole,new QueryWrapper<DtsRole>().eq("id",dtsRole.getId()));
    }

    @Override
    public void delete(Integer id) {
        dtsRoleMapper.deleteById(id);
    }
}
